from django.shortcuts import render,redirect
from django.views import View
from QQLoginTool.QQtool import OAuthQQ

from oauth import sinaweibopy3
from oauth.models import OAuthQQUser
from django.conf import settings
from django.contrib.auth import login
from django.http import JsonResponse , HttpResponse
from users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django_redis import get_redis_connection

# Create your views here.
class QQLoginView(View):
    def get(self,request):

        # 获取登陆成功后的跳转链接
        next = request.GET.get('next')
        if next is None:
            next = '/'

        # 初始化创建qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        login_url = qq.get_qq_url()
        return JsonResponse({'login_url': login_url})


class QQCallBackView(View):

    def get(self,request):
        # 获取code值和stste
        code = request.GET.get('code')
        state = request.GET.get('state')
        if code is None or state is None:

            return JsonResponse({'error':'缺少数据'},status=400)
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=next)

        try:
            # 获取token值
            access_token = qq.get_access_token(code)
            # 获取openid
            open_id = qq.get_open_id(access_token)

        except:
            return JsonResponse({'error': '网络错误'},status=400)

        try:
            # 从数据库中获取openid
            qq_user = OAuthQQUser.objects.get(openid=open_id)
        except:
            # 获取配置文件中的值进行加密并解码
            tjs = TJS(settings.SECRET_KEY,300)
            openid = tjs.dumps({'openid':open_id}).decode()
            return render(request, 'oauth_callback.html',{'token': openid})
        # 如果绑定过进行状态保持登陆
        login(request,qq_user.user)
        response = redirect(state)
        response.set_cookie('username',qq_user.user.username,60*60*24*7)
        return response

    def post(self,request):

        # 获取数据
        data = request.POST
        mobile = data.get('mobile')
        password = data.get('pwd')
        sms_code = data.get('sms_code')
        openid = data.get('access_token')
        # 验证数据
        client = get_redis_connection('verify_code')
        real_sms_code = client.get('sms_code_%s' %mobile).decode()
        if real_sms_code is None:
            return render(request,'oauth_callback.html', {'errmsg': '短信验证失败'})
        if sms_code != real_sms_code:
            return render(request,'oauth_callback.html',{'errmsg': '短信验证码错误'})

        # 验证通过进行数据绑定
        try:
            user = User.objects.get(phone = mobile)
            if not user.check_password(password):
                return render(request,'oauth_callback.html',{'errmsg': '密码错误'})
        except:
            user = User.objects.create_user(username=mobile, mobile= mobile,password= password)
        tjs = TJS(settings.SECRET_KEY,300)

        try:
            data = tjs.loads(openid)
        except:
            return render(request,'oauth_callback.html', {'errmsg': 'openid异常'})
        openid = data.get('openid')
        OAuthQQUser.objects.create(openid = openid,user=user)
        login(request,user)
        response = redirect('/')
        response.set_cookie('username',user.username,60*60*24)

        return response


class SinaLoginView(View):
    def get(self,request):

        # 获取登陆成功后的跳转链接
        next = request.GET.get('next')
        if next is None:
            next = '/'

        # 初始化创建sina对象
        sina = sinaweibopy3.APIClient(app_key=settings.APP_KEY, app_secret=settings.APP_SECRET,
                                        redirect_uri=settings.REDIRECT_URL)
        login_url = sina.get_authorize_url()
        return JsonResponse({'login_url': login_url})
